// pages/bind/bindPhone.js
var config = require('../../utils/config.js')
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {


  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  quickLogin: function(e) {
    var that = this;
    var encryptedData = e.detail.encryptedData;
    var iv = e.detail.iv;
    var key = app.globalData.sessionKey;

    // 解析获取手机号码
    wx.showLoading({
      title: '正在登陆...',
      mask: true
    });

    wx.request({
      url: config.service.decryptData,
      data: {
        timestamp: "12345678",
        sign: "54759d9dc066aa2c80fcb0c87b4c6887",
        key: key,
        encrypt: encryptedData,
        iv: iv,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      method: 'POST',
      success: function(res) {
        var resCode = res.data.code;
        if (resCode == 200) {
          var phoneNumber = res.data.data.phoneNumber;
          // 通过appid,绑定手机号码
          that.bindPhone(phoneNumber);
        } else {
          wx.hideLoading()
          wx.showToast({
            title: res.data.data.errMsg,
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      },
      fail: function(res) {},
      complete: function(res) {},
    })
  },
  bindPhone: function(phoneNumber) {
    var openId = app.globalData.openId;
    wx.request({
      url: config.service.setOpenid,
      data: {
        timestamp: "12345678",
        sign: "11d5d831fdb258876fc7d16f60bd1920",
        username: phoneNumber,
        open_id: openId
      },
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {
        var resCode = res.data.code;
        if (resCode == 200) {
          wx.hideLoading();
          wx.showToast({
            title: '登录成功',
            icon: 'none',
            success: function() {
              wx.navigateBack({
                delta: 999
              });
            }
          })
        }else  {
          wx.hideLoading()
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1500,
            mask: true
          })
        }
      }
    })
  }
})